/*
 * Created: Nov. 13, 2007
 * Creator: David Schneider
 * 
 * DESCRIPTION
 * This class provides the connection interface with the GameHub mote.
 * In connecting it will parse the incoming data, and send commands over 
 * the serial port. Hopefully it will also find where the mote is connected.
 *
 * 
 * The MoteCollection connection should probably be converted into an interface 
 * so that a virtual Bridge can be created.
 */
 
#ifndef MOTEBRIDGE_H_
#define MOTEBRIDGE_H_

//Classes for serial connection
#include "serial/serialcomm.h"
#include "serial/packetbuffer.h"
#include "serial/sharedinfo.h"
#include "NetworkPacket.h"
#include <pthread.h>
#include <string>
#include <sstream>
#include <iostream>
#include "MoteCollection.h"
#include "NetworkPacket.h"

#undef DEBUG
#ifdef DEBUG_MOTEBRIDGE
#include <iostream>
#define DEBUG(message) std::cout << message << std::endl;
#else
#define DEBUG(message) 
#endif

#define DEFAULT_DEVICE "/dev/ttyUSB0"
#define DEFAULT_BAUDRATE 115200

class MoteCollection;

/*!
 * \brief MoteBridge connects a mote attached to the serial port to the MoteCollection.
 * \author Khalid Alhokail, Vineet Gupta, Oren Melzer, David Schneider
 *
 */
class MoteBridge {
public:
	MoteBridge(MoteCollection *pCollection,	const char* device,	int baudrate);
	MoteBridge(MoteCollection *pCollection,	const char* device);
	MoteBridge(MoteCollection *pCollection);
	~MoteBridge();
	bool SendPacket(NetworkPacket& packet);
	bool setLEDs(int moteId, short values);
	bool setSamplingInterval(int moteId, int twentiethsOfASecond);

private:
	//prevent default constructor
	MoteBridge();

	PacketBuffer readBuffer;
	PacketBuffer writeBuffer;
	SerialComm* commInterface;
	sharedControlInfo_t controlLock;
	
	MoteCollection *collection;
	
	/* pthread for serial reading */
    pthread_t readThread;
	
	void processPacket(const NetworkPacket& packet);
	void readerThread();
	
	/* needed to start pthreads */
    friend void* readerThreadHelper(void*);
};

void* readerThreadHelper(void*);

#endif /*MOTEBRIDGE_H_*/
